package mail.verify.slider.selenium;

import mail.selenium.TecentCrawler;
import mail.verify.slider.ImageProcessor;
import mail.verify.slider.MoveEntity;
import mail.verify.slider.TrackMaker;
import org.jsoup.Jsoup;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.han.http.util.Print.printlnInfo;

/**
 * @author: Hanjiafeng
 * @date: Created in 16:30 2019/3/5
 * @desc: 腾讯滑块验证(selenium)
 */
public class TecentSlider {

    static {
        System.setProperty("webdriver.chrome.driver", "A:\\SelfTest\\chromedriver.exe");
    }

    public static Map<String, String> verify(String slideHtml, byte[] imageBytes) throws IOException {
        TecentSlider tecentSlider = new TecentSlider();
        Map<String, String> slideParameterMap = new HashMap<>(9);
        ChromeDriver chromeDriver = new ChromeDriver();
        chromeDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        chromeDriver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        chromeDriver.get(slideHtml);

        /*String originalUrl = Jsoup.parse(chromeDriver.getPageSource()).select("[id=slideBg]").first().attr("src");
        System.out.println(originalUrl);
        TecentCrawler.downloadOriginalImg(0, originalUrl, chromeDriver.manage().getCookies());
        imageBytes = fileToBytes();*/

        if (Objects.isNull(imageBytes)) {
            chromeDriver.quit();
            return null;
        }

        try {
            tecentSlider.move(chromeDriver, imageBytes);
        } catch (IOException e) {
            throw new IOException("移动滑块失败:" + e.getMessage());
        }
        int retryCount = 10;
        //缺口位置
        WebElement ansCodeEle;
        String ansCode = null;
        WebElement vsigEle;
        String vsig = null;
        WebElement cdataEle;
        String cdata = null;
        WebElement websigEle;
        String websig = null;
        WebElement subcapclassEle;
        String subcapclass = null;
        WebElement encryptedTrackEle;
        String encryptedTrack = null;
        WebElement fpinfoEle;
        String fpinfo = null;
        WebElement eksEle;
        String eks = null;
        WebElement tlgEle;
        String tlg = null;
        //最多重复10次,每次等待5秒,到时间后如果还没有获取到,跳出,返回null
        while ((Objects.isNull(ansCode) || Objects.isNull(vsig) || Objects.isNull(cdata) || Objects.isNull(websig)
                || Objects.isNull(subcapclass) || Objects.isNull(encryptedTrack) || Objects.isNull(fpinfo)
                || Objects.isNull(eks) || Objects.isNull(tlg)) && retryCount-- > 0) {
            try {
                Thread.sleep(1000 * 3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                ansCodeEle = chromeDriver.findElementById("vertexCode");
                ansCode = ansCodeEle.getText();
                slideParameterMap.put("vertexCode", ansCode);

                vsigEle = chromeDriver.findElementById("vsigCode");
                vsig = vsigEle.getText();
                slideParameterMap.put("vsigCode", vsig);

                cdataEle = chromeDriver.findElementById("cdataCode");
                cdata = cdataEle.getText();
                slideParameterMap.put("cdataCode", cdata);

                websigEle = chromeDriver.findElementById("websigCode");
                websig = websigEle.getText();
                slideParameterMap.put("websigCode", websig);

                subcapclassEle = chromeDriver.findElementById("subcapclassCode");
                subcapclass = subcapclassEle.getText();
                slideParameterMap.put("subcapclassCode", subcapclass);

                encryptedTrackEle = chromeDriver.findElementById("encryptedTrackCode");
                encryptedTrack = encryptedTrackEle.getText();
                slideParameterMap.put("encryptedTrackCode", encryptedTrack);

                fpinfoEle = chromeDriver.findElementById("fpinfoCode");
                fpinfo = fpinfoEle.getText();
                slideParameterMap.put("fpinfoCode", fpinfo);

                eksEle = chromeDriver.findElementById("eksCode");
                eks = eksEle.getText();
                slideParameterMap.put("eksCode", eks);

                tlgEle = chromeDriver.findElementById("tlgCode");
                tlg = tlgEle.getText();
                slideParameterMap.put("tlgCode", tlg);
            } catch (NoSuchElementException ignore) {
            }
        }
        chromeDriver.close();
        return slideParameterMap;
    }

    public static void main(String... args) throws IOException {
        printlnInfo(verify("F:\\workspace\\java\\MailCrawler\\src\\main\\resources\\cache\\cap_union_new1551941356981.html", null));
    }

    private static byte[] fileToBytes() {
        InputStream inputStream = null;
        byte[] bytes = null;
        try {
            inputStream = new FileInputStream("F:\\workspace\\java\\MailCrawler\\src\\main\\resources\\cache\\hycdn_1_1585757711932845056_0.jpg");
            bytes = inputStream.readAllBytes();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                Objects.requireNonNull(inputStream).close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bytes;
    }

    private void move(ChromeDriver chromeDriver, byte[] imageBytes) throws IOException {

        try {
            Thread.sleep(1000 * 5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        int distance = ImageProcessor.getX(imageBytes) / 2;
        printlnInfo(distance);
        distance -= 30;
        System.exit(0);
        List<MoveEntity> moveEntityList = TrackMaker.t(distance);
        WebElement element = chromeDriver.findElement(By.id("tcaptcha_drag_button"));
        Actions actions = new Actions(chromeDriver);
        actions.clickAndHold(element).perform();
        for (MoveEntity moveEntity : moveEntityList) {
            actions.moveByOffset(moveEntity.getX(), moveEntity.getY()).perform();
            try {
                Thread.sleep(moveEntity.getSleepTime());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        actions.release(element).perform();
    }
}
